<?php

namespace App\Models\Card ;

use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;

use App\Models\Customer\Customer; //商品库存表

use App\Models\Card\CardCouponCode; //活动码池子表

use App\Models\Card\CardCouponCodeGive; //活动码池子表

use App\Models\Card\CardCouponMall;

use App\Models\Mall\MallMaster;

use Illuminate\Support\Facades\DB;

class CardCoupon extends Model
{

    protected $table = 'card_coupon';

    protected $primaryKey = 'card_id';

    public $timestamps = false;

    public $incrementing = false;


    /**
     * 根据uuid查询卡券详情
     * @param $uuid
     * @param string $field
     * @return null
     */
    public static function getFromUuid( $uuid ) {

        if ( empty( $uuid ) ) {
            return null;
        }

        $card = self::where('uuid',$uuid)->first();
        if ( !$card ) {
            return null;
        }
        $card = $card->toArray();

        return $card;
    }

    /**
     * 赠送卡券
     * @param $card_id
     * @param $code
     * @param $user_id
     * @param $give_user_id
     */
    public static function give( $card_id, $code, $user_id, $give_user_id,$remark = '' ) {

        if (!isset($card_id, $code, $user_id, $give_user_id)) {
            return ['code' => 10001, 'message' => '缺少卡券参数'];
        }

        if (!ebsig_is_int($card_id)) {
            return ['code' => 10002, 'message' => '卡券ID不能为空'];
        }
        if (empty($code)) {
            return ['code' => 10003, 'message' => '卡券券码不能为空'];
        }
        if (!ebsig_is_int($user_id)) {
            return ['code' => 10004, 'message' => '缺少会员信息'];
        }
        if (!ebsig_is_int($give_user_id)) {
            return ['code' => 10005, 'message' => '缺少赠送会员信息'];
        }

        $customer =  Customer::select('pcustID','custID','cardNo')->where('pcustID',$give_user_id)->first();
        if ( !$customer ) {
            return ['code' => 10005, 'message' => '会员不存在'];
        }

        try {

            DB::beginTransaction();

            $code_pool =  CardCouponCode::where([
                'barcode'=>$code,
                'activity_id'=>$card_id,
                'pcustID'=>$user_id
            ])
                ->first();

            if ( !$code_pool ) {
                throw new \Exception('赠送的卡券不存在', 10007);
            }
            if ($code_pool->code_status == 2) {
                throw new \Exception('卡券已使用，不能转赠', 10008);
            }
            if ($code_pool->code_status == 3) {
                throw new \Exception('卡券已废弃，不能转赠', 10009);
            }

            CardCouponCode::where(['barcode'=>$code, 'activity_id'=>$card_id, 'pcustID'=>$user_id])->update([
                'pcustID'=>$customer->pcustID,
                'custID'=>$customer->custID,
                'cardNo'=>!empty($customer->cardNo ) ? $customer->cardNo : '' ,
                'member_code'=>$customer->custID,
                'member_code_type'=>0,
                'nick_name'=>''
            ]);

            CardCouponCodeGive::insert([
                'uuid' => makeUuid(),
                'timeStamp' => Carbon::now(),
                'createTime' => Carbon::now(),
                'creator' => $code_pool->custID,
                'barcode' => $code,
                'user_id' => $user_id,
                'give_user_id' => $give_user_id,
                'remark' => $remark
            ]);

            DB::commit();

        } catch (\Exception $e) {

            DB::rollBack();

            return ['code' => $e->getCode(), 'message' => $e->getMessage()];

        }

        return ['code' => 200, 'message' => '赠送成功'];
    }


    /**
     * 检查卡券编号
     * @param string $code 卡券编号
     * @param int $pcustID 会员号
     * @param array $goods_array 商品数组
     * @param int $shop_id 店铺id
     * @param int $platform 购买平台
     * @return array
     */
    public static function checkCoupon( $code, $pcustID, $goods_array, $shop_id = 0, $platform = 0)
    {

        if (!isset($code, $pcustID, $goods_array) || empty($code) || !ebsig_is_int($pcustID) || empty($goods_array)) {
            return array( 'code'=>400, 'message'=>'参数错误' );
        }

        $current_datetime = Carbon::now();

        //查询卡券编号信息
        $coupon_code_array = CardCouponCode::find($code);

        if (!$coupon_code_array) {

            //卡券编号信息没有找到，检查是否是万能码
            $coupon_array = self::where(['wncode' => $code, 'provide_type' => 3, 'useFlg' => 1])->first();
            if ( !$coupon_array ) {
                return ['code' => 10001, 'message' => '卡券不存在'];
            }
            $coupon_array = $coupon_array->toArray();

            //检查卡券是否已过期
            if ( $coupon_array['use_end_time'] < $current_datetime ) {
                return ['code' => 10002, 'message' => '卡券已过期'];
            }
            $coupon_code_array = array(
                'code_start_time' => $coupon_array['use_start_time'],
                'code_end_time' => $coupon_array['use_end_time'],
            );
        } else {

            $coupon_code_array = $coupon_code_array->toArray();

            //检查是否是当前会员的卡券
            if (!empty($coupon_code_array['pcustID']) && $coupon_code_array['pcustID'] != $pcustID) {
                return ['code' => 10003, 'message' => '卡券不存在'];
            }

            //检查卡券是否已过期
            if ($coupon_code_array['code_end_time'] < $current_datetime) {
                return ['code' => 10004, 'message' => '卡券已过期'];
            }

            //检查卡券是否已使用
            if ( $coupon_code_array['code_status'] == 2 ) {
                return ['code' => 10005, 'message' => '卡券已使用'];
            }

            //查询卡券信息
            $coupon_array = self::where(['card_id' => $coupon_code_array['activity_id'], 'useFlg' => 1])->first();
            if ( !$coupon_array ) {
                return ['code' => 10006, 'message' => '卡券不存在'];
            }
            $coupon_array = $coupon_array->toArray();

        }

        if ($coupon_array['support_condition'] == 2) {
            return ['code' => 10007, 'message' => '此卡券只支持线下使用'];
        } else {
            if ($platform == 4 && $coupon_array['app_usable'] != 1) {
                return ['code' => 10008, 'message' => '此卡券不支持当前平台使用'];
            } else if ($platform == 3 && $coupon_array['b2c_usable'] != 1) {
                return ['code' => 10009, 'message' => '此卡券不支持当前平台使用'];
            } else if ($platform == 5 && $coupon_array['pad_usable'] != 1) {
                return ['code' => 10010, 'message' => '此卡券不支持当前平台使用'];
            } else if (in_array($platform, array(0, 1)) && $coupon_array['wap_usable'] != 1) {
                return ['code' => 10011, 'message' => '此卡券不支持当前平台使用'];
            }
        }

        //大区筛选
        if ( isset($coupon_array['mallareaID']) && !empty($coupon_array['mallareaID']) ) {
            $mall_data = MallMaster::where(['mallID' => $shop_id, 'mallareaID' => $coupon_array['mallareaID']])->first();
            if ( !$mall_data ) {
                return ['code' => 10012, 'message' => '不在优惠券使用范围，无法使用'];
            }
        }

        //门店筛选
        if (isset($coupon_array['mall_support_type']) && $coupon_array['mall_support_type'] == 2) {
            $card_coupon_mall = CardCouponMall::where(['relation_type' => 1, 'card_id' => $coupon_array['card_id'], 'relation_id' => $shop_id])->first();
            if ( !$card_coupon_mall ) {
                return ['code' => 10013, 'message' => '不在优惠券使用范围，无法使用'];
            }
        }

        //符合条件商品总金额、总数量
        $total_money = 0;
        $goods_amount = 0;

        //筛选商品
        $select_goods = json_decode($coupon_array['selectorID_json'], true);
        foreach ($goods_array as $goods) {
            if ($select_goods['selector_type'] == 2) {
                if ($select_goods['selector_relation'] && !in_array($goods['postID'], $select_goods['select_goods']))
                    continue;
                if (!$select_goods['selector_relation'] && in_array($goods['postID'], $select_goods['select_goods']))
                    continue;
            }
            $total_money += $goods['price'] * $goods['goodsAmount'];
            $goods_amount += $goods['goodsAmount'];
        }

        //没有符合条件的商品
        if ($goods_amount == 0) {
            return ['code' => 10014, 'message' => '没有符合优惠券条件的商品'];
        }

        //商品金额不满足优惠券使用限额
        if ($total_money < $coupon_array['limit_money']) {
            return ['code' => 10015, 'message' => '商品金额不满足优惠券使用限额'];
        }

        //如果是折扣券，转换成减免的金额
        if ( $coupon_array['card_type'] == 2 ) {
            $coupon_array['amount'] = $total_money * (1-$coupon_array['discount']);
        }

        //编号卡券没有绑定会员
        if ($coupon_array['provide_type'] == 1 && empty($coupon_code_array['pcustID'])) {
            CardCouponCode::where('barcode', $code)->update(['pcustID' => $pcustID]);
        }

        $return_array = array(
            'code' => $code,
            'cardType' => $coupon_array['card_type'],
            'amount' => $coupon_array['amount'],
            'discount' => $coupon_array['discount'],
            'couponID' => $coupon_array['card_id'],
            'couponName' => $coupon_array['card_name'],
            'code_start_time' => $coupon_code_array['code_start_time'],
            'code_end_time' => $coupon_code_array['code_end_time'],
            'start_date' => date('Y-m-d', strtotime($coupon_code_array['code_start_time']) ),
            'end_date' => date('Y-m-d', strtotime($coupon_code_array['code_end_time']) ),
            'code_limit_amount' => $coupon_array['limit_money']
        );

        return ['code' => 200, 'message' => 'ok', 'data'=>$return_array];

    }



    /**
     * 激活优惠券【商城】
     * @param $pcustID
     * @param $coupon_code
     * @param bool|true $isTransaction
     * @return array
     * @throws Exception
     */
    public static function activeCoupon($pcustID, $coupon_code, $isTransaction = true)
    {

        if (!isset($pcustID, $coupon_code) || !ebsig_is_int($pcustID)) {
            return ['code' => 400, 'message' => '参数错误'];
        }

        if (empty($coupon_code)) {
            return ['code' => 400, 'message' => '请输入券激活码'];
        }

        $customer = Customer::select('pcustID','custID','cardNo')->where('pcustID',$pcustID)->first();
        if ( !$customer ) {
            return ['code' => 400, 'message' => '会员不存在'];
        }
        $customer = $customer->toArray();

        $current_datetime = Carbon::now();

        //查询卡券编号信息
        $coupon_code_array = CardCouponCode::find($coupon_code);

        if (!$coupon_code_array) {

            //卡券编号信息没有找到，检查是否是万能码
            $coupon_array = self::where(['wncode' => $coupon_code, 'provide_type' => 3, 'useFlg' => 1])->first();
            if ( !$coupon_array ) {
                return ['code' => 404, 'message' => '卡券不存在'];
            }
            $coupon_array = $coupon_array->toArray();

            //判断领取次数
            $cust_coupon_num = CardCouponCode::where(['activity_id'=>$coupon_array['card_id'],'pcustID'=>$pcustID])->count();
            if ($cust_coupon_num >= $coupon_array['repeat_count']) {
                return ['code' => 409, 'message' => '该卡券每人限领' . $coupon_array['repeat_count'] . '次！'];
            }

            if( $current_datetime < $coupon_array['use_start_time'] || $current_datetime > $coupon_array['use_end_time'] ){
                return ['code'=>400, 'message'=>'卡券不在使用时间范围内'];
            }

            if ($coupon_array['total_num'] == $coupon_array['getNum']) {
                return ['code'=>400, 'message'=>'卡券没有找到'];
            }

            $code_amount = 0;
            $discount = 0;
            $limitMoney = 0;
            $code_type = 0;

            if ($coupon_array['card_type'] == 1) {
                $code_type = 6;
                $limitMoney = $coupon_array['limit_money'];
                $code_amount = $coupon_array['amount'];
            } else if ($coupon_array['card_type'] == 2) {
                $code_type = 7;
            } else if ($coupon_array['card_type'] == 5) {
                $code_type = 10;
                $limitMoney = $coupon_array['limit_money'];
            }

            $code_startTime = $coupon_array['use_start_time'];
            $code_endTime = $coupon_array['use_end_time'];
            if ($coupon_array['time_type'] != 1) {
                $code_startTime = date('Y-m-d H:i:s',strtotime('+' . $coupon_array['valid_begin_day'] . ' day'));
                $code_endTime = date('Y-m-d H:i:s',strtotime('+' . $coupon_array['valid_day'] . ' day', strtotime($code_startTime)));
            }

            //万能码生码
            $activity_code_pool = new CardCouponCode();
            $activity_code_pool->uuid = makeUuid();
            $activity_code_pool->timeStamp = $current_datetime;
            $activity_code_pool->creator = 'system';
            $activity_code_pool->createTime = $current_datetime;
            $activity_code_pool->barcode = $coupon_array['wncode'];
            $activity_code_pool->code_type = $code_type;
            $activity_code_pool->pcustID = $pcustID;
            $activity_code_pool->custID = $customer['custID'];
            $activity_code_pool->cardNo = $customer['cardNo'];
            $activity_code_pool->member_code_type = 1;
            $activity_code_pool->activity_id = $coupon_array['card_id'];
            $activity_code_pool->activity_uuid = $coupon_array['uuid'];
            $activity_code_pool->activity_name = $coupon_array['card_name'];
            $activity_code_pool->code_start_time = $code_startTime;
            $activity_code_pool->code_end_time = $code_endTime;
            $activity_code_pool->get_time = $current_datetime;
            $activity_code_pool->code_status = 1;
            $activity_code_pool->code_verify_type = $coupon_array['is_mobile_verify'] == 1 ? 1 : 2;
            $activity_code_pool->code_amount = $code_amount;
            $activity_code_pool->code_discount = $discount;
            $activity_code_pool->code_limit_amount = $limitMoney;
            $activity_code_pool->code_use_type = $coupon_array['card_type'];
        } else {

            if (!in_array($coupon_code_array['code_use_type'],  array(1, 2, 5))) {
                return ['code'=>404, 'message'=>'卡券没有找到'];
            }

            if ($coupon_code_array['code_status'] != 0) {
                return ['code'=>400, 'message'=>'卡券已被激活， 请检查卡券'];
            }

            if ($coupon_code_array['code_end_time'] < $current_datetime) {
                return ['code'=>400, 'message'=>'您的激活码已过期，请输入有效的激活码'];
            }

            $coupon_array = self::find($coupon_code_array['activity_id']);
            if ( !$coupon_array ) {
                return ['code'=>404, 'message'=>'卡券没有找到'];
            }

        }

        try {

            if ($isTransaction) {
                DB::beginTransaction();
            }

            if (isset($activity_code_pool)) {
                $activity_code_pool->save();
                $coupon_code_array = CardCouponCode::where(['barcode'=>$coupon_array['wncode'],'pcustID'=>$pcustID,'code_status'=>1])->first();
                if (!$coupon_code_array) {
                    throw new \Exception('卡券领取失败', 400);
                }
                $coupon_code_array = $coupon_code_array->toArray();
            } else {
                CardCouponCode::where(['barcode' => $coupon_code ])->update(['pcustID'=>$pcustID,'custID'=>$customer['custID'],'code_status'=>1,'get_time'=>$current_datetime]);
            }

            self::where(['card_id' => $coupon_array['card_id'] ])->increment('getNum');

            $return_array = array(
                'code' => $coupon_code,
                'card_type' => $coupon_array['card_type'],
                'amount' => $coupon_array['amount'],
                'discount' => $coupon_array['discount'],
                'coupon_id' => $coupon_code_array['activity_id'],
                'coupon_name' => $coupon_code_array['activity_name'],
                'code_start_time' => $coupon_code_array['code_start_time'],
                'code_end_time' => $coupon_code_array['code_end_time'],
                'start_date' => date('Y-m-d' , strtotime($coupon_code_array['code_start_time'])),
                'end_date' => date('Y-m-d' , strtotime($coupon_code_array['code_end_time'])),
                'code_limit_amount' => $coupon_code_array['code_limit_amount']
            );

            if( $isTransaction ){
                DB::commit();
            }

            return ['code'=>200, 'message'=>'卡券激活成功', 'data'=>$return_array];

        } catch (\Exception $e) {

            if( $isTransaction ){
                DB::rollBack();
            }

            return ['code' => $e->getCode(), 'message' => $e->getMessage()];

        }



    }

}
